<?php

class License extends MY_SecuredController {

	public function __construct() {
		parent::MY_SecuredController();

		$this->requireRole('User');
		
		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
	
        $this->lang->load('home');
        $this->lang->load('profile/license');
	}
	
	public function index($civlid) {
		$this->_preRender($civlid);
		
		$person = PersonModel::getPerson($civlid);
		if (!$this->_checkAdminClub($person)) {
            return false;
        }
		
		$data['person'] = $person;
		$data['pilot'] = $person->Pilot;
		
		$this->render('profile/license/index', $data);
	}

	public function add($civlid) {
		$this->requireRole('Admin');
		
		$this->_preRender($civlid);

		$person = PersonModel::getPerson($civlid);
        if (!$this->_checkAdminClub($person)) {
            return false;
        }
		
		$pilot = $person->Pilot;
        
        $data['person'] = $person;
        $data['pilot'] = $pilot;
		
		if (!$this->input->post('action')) {
			$data['licenses'] = array();
			$this->_addPilotLicenses($person, $data);	
			
			$q = Doctrine_Query::create()
			    ->select('p.id as id, p.name as name')
			    ->from('personModel p, pilotLicenseModel pl, licenseModel l')
			    ->where('p.id = pl.pilot_id and pl.license_id = l.id and l.id = ?', 6);

			log_message('debug', 'Executed query ->> '.$q);
			    
			$rs = $q->execute();
			    
			$data['examiners'] = $rs->toKeyValueArray('id','name');
			$this->render('profile/license/add', $data);	
		}
		else {
			$license = Doctrine::getTable('LicenseModel')->find($this->input->post('license'));
			$data['licenses'] = array();
			$this->_addPilotLicenses($person, $data);
								
			if ($license) {
				$index = count($pilot->Licenses) == 0? 0 : count($pilot->Licenses);

				$pilot->Licenses[$index] = $license;
				try {
					$pilot->save();
				}
				catch (Exception $e) {
					$data['pilot'] = $pilot;
					
					$this->render('profile/license/add', $data, $this->error(array(
						'message' => 'Ooops, the license could not be added - please try again later.',
						'exception' => $e
					)));
					return;
				}

				foreach ($pilot->PilotLicenseModel as $pc):
					if ($pc->license_id == $license->id):
						$pc->number =  $this->input->post('number');
						$pc->issued = $this->input->post('issued');
						$pc->renewed = $this->input->post('renewed');
						$pc->expires = $this->input->post('expires');
						
						if ($this->input->post('examiner')) {
                            $examiner = PersonModel::getPerson($this->input->post('examiner'));
                            
                            if ($examiner != null) {
                                $pc->Examiner = $examiner;
                            }
						}

						try {
							$pc->save();
						}
						catch (Exception $e) {
							$this->render('profile/license/index', $data, $this->error(array(
								'message' => 'Ooops, the license could not be added - please try again later.',
							'	exception' => $e
							)));
							return;
						}

						break;
					endif;
				endforeach;

				$this->redirect('profile/license/index/'.$person->id, 'License has been successfully added!');
			}
		}
	}

    public function edit($civlid, $licenseid) {
        $this->requireRole('Admin');
        $this->_preRender($civlid);

        $person = PersonModel::getPerson($civlid);
        if (!$this->_checkAdminClub($person)) {
            return false;
        }
        
        $pilot = $person->Pilot;

        if (!$this->input->post('action')) {
            $data['person'] = $person;
            $data['pilot'] = $person->Pilot;

            $q = Doctrine_Query::create()
                ->select('p.id as id, p.name as name')
                ->from('personModel p, pilotLicenseModel pl, licenseModel l')
                ->where('p.id = pl.pilot_id and pl.license_id = l.id')
                ->andWhere('l.id = ?', 6)
                ->andWhere('p.id <> ?', $person->id);

            log_message('debug', 'Executed query ->> '.$q);
                
            $rs = $q->execute();
                
            $data['examiners'] = $rs->toKeyValueArray('id','name');
            $data['examiners'][''] = '';
            
            foreach ($pilot->Licenses as $g) {
                if ($g->id == $licenseid) {
                    $data['license'] = $g;
                    $data['pilot_license'] = $g->PilotLicenseModel[0];

                    $this->render('profile/license/edit', $data);
                    break;
                }
            }
        }
        else {
            log_message('debug', "editing record $licenseid");

            foreach ($pilot->PilotLicenseModel as $pc) {
                if ($pc->license_id == $licenseid) {
                    $pc->number =  $this->input->post('number');
                    $pc->issued = $this->input->post('issued');
                    $pc->renewed = $this->input->post('renewed');
                    $pc->expires = $this->input->post('expires');

                    if ($this->input->post('examiner')) {
                    	log_message('debug', '>>> found examiner: '.$this->input->post('examiner'));
                    	
                        $examiner = PersonModel::getPerson($this->input->post('examiner'));
                            
                        if ($examiner != null) {
                            $pc->Examiner = $examiner;
                        }
                    }
                    else if ($pc->Examiner->id != '') {
                    	$pc->Examiner = null;
                    }
                    
                    try {
                        $pc->save();
                    }
                    catch (Exception $e) {
                        $this->render('profile/license/index', $data, $this->error(array(
                            'message' => 'Ooops, the license could not be added - please try again later.',
                            'exception' => $e
                        )));
                        return;
                    }
                    $this->redirect('profile/license/index/'.$person->id, 'License has been successfully updated!');
                    break;

                }
            }

            $this->redirect('profile/license/index/'.$person->id, 'License not found?');
        }
    }
	
	public function delete($civlid, $licenseid = null) {
		$this->requireRole('Admin');
		$this->_preRender($civlid);

		$person = PersonModel::getPerson($civlid);
        if (!$this->_checkAdminClub($person)) {
            return false;
        }
		
        $licenses = $person->Pilot->PilotLicenseModel;
            
        $data['person'] = $person;
        $data['pilot'] = $person->Pilot;
        $data['pilot'] = $person->Pilot;

		
		if ($this->input->post('action')) {
			foreach ($licenses as $c):
				if ($this->input->post('lid_'.$c->license_id) != ""):
					try {
						$c->delete();
					}
					catch (Exception $e) {
						$this->render('profile/license/index', $data, $this->error(array(
							'message' => 'Ooops, one or more licenses could not be deleted.',
							'exception' => $e
						)));
						return;
					}
				endif;
			endforeach;
			
			$this->redirect('profile/license/index/'.$person->id, 'License has been successfully deleted!');
		}
        else if ($licenseid != null) {
            foreach ($licenses as $g) {
                if ($g->license_id == $licenseid) {
                    try {
                        $g->delete();
                        $this->redirect('profile/license/index/'.$person->id, 'License has been successfully deleted!');
                    }
                    catch (Exception $e) {
                        $this->render('profile/license/index', $data, $this->error(array(
                            'message' => 'Ooops, one or more licenses could not be deleted.',
                            'exception' => $e
                        )));
                        return;
                    }
                }
            }
                
            $this->render('profile/license/index', $data, $this->error(array(
                'message' => "License '$licenseid' could not be found!"
            )));
        }
	}
	
	private function _addPilotLicenses(&$person, &$data) {
		$licenses = Doctrine::getTable('LicenseModel')->findAll();
		$data['licenses'] = array();
			
		$pilotLicenses = array();
		foreach ($person->Pilot->Licenses as $pl):
			$pilotLicenses[] = $pl->id;
		endforeach;

		foreach ($licenses as $l):
			if (!in_array($l->id, $pilotLicenses, true)):
				$data['licenses'][$l->id] = $l->issuer.' - '.$l->level;
			endif;
		endforeach;
	}
}
?>
